<template>
  <div v-loading="loading">
    <h1 class="mod-title">
      <span class="ico-wechat" />
      <span class="text">微信扫码支付</span>
    </h1>
    <div class="mod-ct">
      <div class="order" />
      <div class="amount">￥{{ appCost }}</div>
      <div id="qrcode" class="qr-image" />

      <div id="orderDetail" class="detail">
        <dl class="detail-ct">
          <dt>商家</dt>
          <dd id="storeName">J博士</dd>
          <dt>购买物品</dt>
          <dd id="productName">{{ appName }}</dd>
          <dt>商户订单号</dt>
          <dd id="billId">{{ orderParam.outTradeNo }}</dd>
          <dt>创建时间</dt>
          <dd id="createTime">{{ orderDate }}</dd>
        </dl>
        <!-- <a href="javascript:void(0)" class="arrow"> -->
        <!-- <i class="ico-arrow-wechat"></i> -->
        <div id="qrCode" ref="qrCodeDiv" style="margin-top: 15px;line-height: 100px;border: 1px solid green;text-align:center;" />
        <!-- </a> -->

      </div>
      <div class="tip">
        <span class="dec dec-left" />
        <span class="dec dec-right" />
        <div class="ico-scan-wechat" />
        <div class="tip-text">
          <p>请使用微信扫一扫</p>
          <p>扫描二维码完成支付</p>
        </div>
      </div>
      <div class="tip-text" />
    </div>
    <div class="foot">
      <div class="inner">
        <p>手机用户可保存上方二维码到手机中</p>
        <p>在微信扫一扫中选择“相册”即可</p>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import { createQRCode } from '@/api/market/index'
import { orderQuery } from '@/api/market/index'

export default {
  name: 'QrCode',
  data() {
    return {
      loading: false,
      orderParam: {
        outTradeNo: undefined
      },
      data: {
        appId: this.$route.query.appId
      },
      appName: this.$route.query.appName,
      appCost: this.$route.query.appCost,
      orderDate: undefined,
      // 轮询
      polling: ''
    }
  },
  mounted: function() {
    this.$nextTick(function() {
      this.loading = true
      this.currentTime()
      createQRCode(this.data).then(res => {
          if (res.code === 200) {
            this.bindQRCode(res.data.urlCode)
            this.orderParam.outTradeNo = res.data.outTradeNo
            this.loading = false
            // 开始轮询
            this.getDateLoop()
          }
      }).catch((r) => {
        console.error(r)
        this.loading = true
      })
    })
  },
  methods: {
    bindQRCode: function(data) {
      new QRCode(this.$refs.qrCodeDiv, {
        text: data,
        width: 200,
        height: 200,
        colorDark: '#333333', // 二维码颜色
        colorLight: '#ffffff', // 二维码背景色
        correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
      })
    },
    /**
     * 查询微信订单号
     */
    orderQuery() {
      orderQuery(this.orderParam).then(res => {
          if (res.code === 200 && res.data === 'Y') {
            this.$message.success('支付成功!即将前往JStore下载应用')
            setTimeout(() => {
              this.$router.push('/appStore')
            }, 2000)
          }
      })
    },
    /**
    * 获取当前时间
    */
    currentTime() {
        var date = new Date()
        var year = date.getFullYear() // 月份从0~11，所以加一
        // const month = date.getMonth()
        var dateArr = [
            date.getMonth() + 1,
            date.getDate(),
            date.getHours(),
            date.getMinutes(),
            date.getSeconds()
        ]
        // 如果格式是MM则需要此步骤，如果是M格式则此循环注释掉
        for (var i = 0; i < dateArr.length; i++) {
            if (dateArr[i] >= 1 && dateArr[i] <= 9) {
                dateArr[i] = '0' + dateArr[i]
            }
        }
        var strDate =
            year +
            '-' +
            dateArr[0] +
            '-' +
            dateArr[1] +
            ' ' +
            dateArr[2] +
            ':' +
            dateArr[3] +
            ':' +
            dateArr[4]
            this.orderDate = strDate
    },
    /**
     * 轮询查询微信支付状态
     * @param {*} timeout
     */
    getDateLoop(timeout = 3000) { // timeout可以写死，也可以动态
      console.log('开始轮询') // 执行语句
      this.polling = setInterval(() => {
        if (this.orderParam.outTradeNo) {
          this.orderQuery()
        }
        console.log('查询...') // 轮询中，执行语句
      }, timeout)
    }
  },
  beforeRouteLeave(to, from, next) { // 路由跳转前，清除轮询
    next()
    if (this.polling) {
    clearInterval(this.polling)
    this.polling = null
    }
  }
}
</script>
<style lang='scss' scoped>
#qrCode {
  display: inline-block;
  margin: 0 auto; /*水平居中*/
  position: relative;
  top: 15%;

  img {
    width: 200px;
    height: 200px;
    background-color: #fff; //设置白色背景色
    padding: 6px; // 利用padding的特性，挤出白边
  }
}
</style>
